package tools

import (
	"context"
	"encoding/json"
	"fmt"

	"gitee.com/EagleMao/eino_n9e_tool/pkg/logger"
	"github.com/cloudwego/eino/components/tool"
	"github.com/cloudwego/eino/schema"
)

func GetQueryPromTool(backService *N9EService) tool.InvokableTool {
	return &ToolPromQuery{
		backService: backService,
	}
}

type ToolPromQuery struct {
	backService *N9EService
}

type MetricsQueryParam struct {
	Ident string `json:"ident"`
	Query string `json:"query"`
	Start string `json:"start"`
	End   string `json:"end"`
	Step  string `json:"step"`
}

func (t ToolPromQuery) Info(ctx context.Context) (*schema.ToolInfo, error) {
	toolInfo := &schema.ToolInfo{
		Name: "prom_query",
		Desc: "根据指标查询Prometheus监控数据",
		ParamsOneOf: schema.NewParamsOneOfByParams(
			map[string]*schema.ParameterInfo{
				"query": {
					Type:     schema.String,
					Desc:     "指标名称,如 cpu_usage_active",
					Required: true,
				},
				"ident": {
					Type:     schema.String,
					Desc:     "实例名称或者主机名称",
					Required: false,
				},
				"start": {
					Type:     schema.String,
					Desc:     "开始时间,采用时间戳格式",
					Required: false,
				},
				"end": {
					Type:     schema.String,
					Desc:     "结束时间,采用时间戳格式",
					Required: false,
				},
			},
		),
	}
	return toolInfo, nil
}
func (t ToolPromQuery) InvokableRun(ctx context.Context, argumentsInJSON string, opts ...tool.Option) (string, error) {
	params := &MetricsQueryParam{}
	err := json.Unmarshal([]byte(argumentsInJSON), params)
	if err != nil {
		return "", err
	}
	resp, err := t.backService.GetMetrics(*params)
	if err != nil {
		return "", err
	}

	res, err := json.Marshal(resp)

	if err != nil {
		logger.Info(fmt.Sprintf("%v 序列号失败 %v", resp, err))
		return "", err
	}

	return string(res), err
}
